package com.rimi.bbs.controller;

import com.rimi.bbs.bean.JsonResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/file")
public class FileController {

    @Value("${file.uploadFolder}")
    private String uploadFolder;

    @PostMapping("/upload")
    @ResponseBody
    public Object upload(@RequestParam("file") MultipartFile file, HttpServletRequest request){
        if (file.isEmpty()) {
            return JsonResult.error("上传失败，请选择文件");
        }
        //文件保存路径
        System.out.println("文件保存路径:"+uploadFolder);
        //原文件名
        String originalFilename = file.getOriginalFilename();
        //获取文件后缀
        String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        //文件名
        String fileName=System.currentTimeMillis()+fileType;
        //
        try {
            File file1 = new File(uploadFolder+"/images/", fileName);
            if(!file1.getParentFile().exists()){
                file1.getParentFile().mkdirs();
            }
            file.transferTo(file1);
            return JsonResult.ok("文件上传成功").put("url","/images/"+fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return JsonResult.error("文件上传失败");
    }


}
